package org.nowcoder.leetcode.BTree;


import java.util.Stack;

/**
 * Title  : 226. Invert Binary Tree
 * Source : https://leetcode.cn/problems/invert-binary-tree/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-08-29
 */

public class LeetCode_226 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode node = root.left;
        root.left = root.right;
        root.right = node;

        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    public TreeNode invertTreeByPreOrder(TreeNode root) {
        if (root == null) return null;
        Stack<TreeNode> sta = new Stack<>();
        sta.push(root);
        while (!sta.isEmpty()) {
            TreeNode node = sta.pop();
            //交换左右节点
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
            if (node.left != null) {
                sta.push(node.left);
            }
            if (node.right != null) {
                sta.push(node.right);
            }
        }
        return root;
    }
}
